package com.lilicould.controller;

import com.lilicould.entity.Account;
import com.lilicould.entity.Employee;
import com.lilicould.service.impl.AccountServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/register/employee")
public class RegisterEmployeeController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 声明 service
        AccountServiceImpl accountService = new AccountServiceImpl();

        // 读取账号有关信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String accountType = "employee";
        // 用户ID在Service中自动生成
        String userId = null;
        byte status = 1;

        // 检查用户名是否已存在
        if (accountService.checkUsername(username)) {
            req.setAttribute("error", "用户名已存在");
            req.getRequestDispatcher("/employee/info").forward(req, resp);
        }


        //读取员工有关信息
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        Double salary = Double.parseDouble(req.getParameter("salary"));
        int roleIdSelected = Integer.parseInt(req.getParameter("roleId"));
        int skillSelected = Integer.parseInt(req.getParameter("skill"));
        String skill = "";
        String roleId = "";
        if (roleIdSelected == 1) {
            roleId = "manager";
            skill = "管理楼宇";
        }else if (roleIdSelected == 2){
            roleId = "maintenance";
            switch (skillSelected) {
                case 1:
                    skill = "水电维修";
                    break;
                case 2:
                    skill = "电梯维修";
                    break;
                case 3:
                    skill = "其他";
                    break;
            }
        }

        // 存入账号类和员工类对象
        Account account = new Account(null, username, password, accountType, null, status);
        Employee employee = new Employee(null, name, phone, salary);

        //调用员工注册方法
        boolean result = accountService.registerEmployee(account, employee, roleId,skill);
        if(result) {
            req.getSession().setAttribute("error", null);
            req.getRequestDispatcher("/employee/info").forward(req, resp);
        }else {
            req.getSession().setAttribute("error", "注册失败");
            req.getRequestDispatcher("/employee/info").forward(req, resp);
        }

    }
}
